package com.kds.changzhou.utility;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author 孔德嵩
 * @version AES 编解码工具
 */
public class AESUtils {

    private final byte[] key;

    private final byte[] iv;

    private Cipher cipher;

    private SecretKeySpec secretKey;

    private IvParameterSpec _iv;

    public AESUtils(byte[] key, byte[] iv) {
        this.key = key;
        this.iv = iv;
        init();
    }

    private void init() {

        try {
            cipher = Cipher.getInstance("AES/CBC/NoPadding");
            secretKey = new SecretKeySpec(key, "AES");
            _iv = new IvParameterSpec(iv);

        } catch (Exception e) {

            e.printStackTrace();
        }

    }

    public byte[] encrypt(byte[] strToEncrypt) throws Exception {

        int blockSize = cipher.getBlockSize();

        int plaintextLength = strToEncrypt.length;
        int k = plaintextLength % blockSize;
        if (k != 0) {
            plaintextLength = plaintextLength + (blockSize - k);
        }
        byte[] plaintext = new byte[plaintextLength];
        System.arraycopy(strToEncrypt, 0, plaintext, 0, strToEncrypt.length);

        cipher.init(Cipher.ENCRYPT_MODE, secretKey, _iv);
        return cipher.doFinal(plaintext);

    }

    public byte[] decrypt(byte[] strToDecrypt) throws Exception {

        cipher.init(Cipher.DECRYPT_MODE, secretKey, _iv);
        byte[] raw = cipher.doFinal(strToDecrypt);

        return raw;

    }

}
